package com.fc.mall.portal.service.impl;

import com.fc.mall.exception.ServiceException;
import com.fc.mall.mapper.UmsMemberAccountMapper;
import com.fc.mall.mapper.UmsMemberMapper;
import com.fc.mall.mapper.UmsWithdrawMapper;
import com.fc.mall.model.UmsMember;
import com.fc.mall.model.UmsMemberAccount;
import com.fc.mall.model.UmsMemberAccountExample;
import com.fc.mall.model.UmsWithdraw;
import com.fc.mall.model.UmsWithdrawExample;
import com.fc.mall.portal.dto.WithdrawCreate;
import com.fc.mall.portal.service.ConfigService;
import com.fc.mall.portal.service.SmsService;
import com.fc.mall.portal.service.UmsWithdrawService;
import com.fc.mall.util.Constants;
import com.fc.mall.util.DateTimeHelper;
import com.github.pagehelper.PageHelper;
import ma.glasnost.orika.MapperFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.List;

@Service
public class UmsWithdrawServiceImpl implements UmsWithdrawService {

    @Autowired
    private UmsWithdrawMapper umsWithdrawMapper;

    @Autowired
    private UmsMemberAccountMapper memberAccountMapper;

    @Autowired
    private UmsMemberMapper memberMapper;

    @Autowired
    private ConfigService configService;

    @Autowired
    MapperFacade mapperFacade;

    @Autowired
    private SmsService smsService;

    @Override
    @Transactional
    public UmsWithdraw withdraw(Long memberId, WithdrawCreate withdrawCreate) {
        UmsMemberAccountExample example = new UmsMemberAccountExample();
        example.createCriteria()
                .andMemberIdEqualTo(memberId);
        List<UmsMemberAccount> accounts = memberAccountMapper.selectByExample(example);
        if (accounts == null || accounts.size() == 0) {
            throw new ServiceException("未找到账户");
        }

        UmsMemberAccount account = accounts.get(0);
        if (account.getAbleAmount() < withdrawCreate.getAmount()) {
            throw new ServiceException("可提现余额不足");
        }

        boolean isClosed = configService.getRequiredBooleanConfig(Constants.withdrawConfig.CLOSE.getExternalCode());
        if (isClosed) {
            throw new ServiceException("提现已关闭");
        }

        int minAmount = configService.getOptionalIntConfig(Constants.withdrawConfig.MIN_AMOUNT.getExternalCode(), 0);
        if (minAmount > 0 && withdrawCreate.getAmount() < minAmount) {
            throw new ServiceException("不满足最低提现金额");
        }

        int fee = configService.getOptionalIntConfig(Constants.withdrawConfig.FEE.getExternalCode(), 0);
        int amountFee = fee > 0 ? withdrawCreate.getAmount() * fee / 100 : 0;
        UmsMember member = memberMapper.selectByPrimaryKey(memberId);
        UmsWithdraw withdraw = UmsWithdraw.builder()
                .memberId(memberId)
                .amountFee(amountFee)
                .amountMoney(withdrawCreate.getAmount() - amountFee)
                .nickname(member.getNickname())
                .wx(member.getWxOpenId())
                .wxName(member.getNickname())
                .applyDate(new Date())
                .status(0)
                .build();
        mapperFacade.map(withdrawCreate, withdraw);

        Long ableAmount = account.getAbleAmount() - (withdrawCreate.getAmount()*100);
        account.setAbleAmount(ableAmount);
        memberAccountMapper.updateByPrimaryKeySelective(account);
        umsWithdrawMapper.insert(withdraw);

        try {
            String nickName = URLDecoder.decode(member.getNickname(), "utf-8");
            smsService.approvalNotice(member.getId(), nickName, "提现申请", "等待审核", DateTimeHelper.getStringFromDate(new Date(), DateTimeHelper.PAYLOAD_DATEONLY));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return withdraw;
    }

    @Override
    public List<UmsWithdraw> list(Long memberId, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        UmsWithdrawExample example = new UmsWithdrawExample();
        example.createCriteria()
                .andMemberIdEqualTo(memberId);
        example.setOrderByClause("apply_date desc");
        List<UmsWithdraw> umsWithdrawList = umsWithdrawMapper.selectByExample(example);
        return umsWithdrawList;
    }
}
